#include <time.h>
#include <QTime>
#include "RealTimcsEx.h"

using namespace std;

///////////////////////ticks//////////////////////////
CRealTimcsEx::CRealTimcsEx(string name)
{
#ifdef Q_OS_WINDOWS
	m_startTicks.QuadPart = 0;
	m_endTicks.QuadPart = 0;
#else
    m_startTicks = 0;
    m_endTicks = 0;
#endif
	m_name = name;
	m_dMillisecond = 0;
	m_llMicrosecond = 0;

	m_bStart = false;
#ifdef Q_OS_WINDOWS
	QueryPerformanceFrequency(&m_freq);
#endif
}
CRealTimcsEx::CRealTimcsEx()
{
#ifdef Q_OS_WINDOWS
	m_startTicks.QuadPart = 0;
	m_endTicks.QuadPart = 0;
#else
    m_startTicks = 0;
    m_endTicks = 0;
#endif
	m_name = "default";
	m_dMillisecond = 0;
	m_llMicrosecond = 0;

	m_bStart = false;
#ifdef Q_OS_WINDOWS
	QueryPerformanceFrequency(&m_freq);
#endif
}
CRealTimcsEx::~CRealTimcsEx()
{}
void CRealTimcsEx::Reset()
{
#ifdef Q_OS_WINDOWS
    m_startTicks.QuadPart = 0;
    m_endTicks.QuadPart = 0;
#else
    m_startTicks = 0;
    m_endTicks = 0;
#endif

	m_dMillisecond = 0;
	m_llMicrosecond = 0;

	m_bStart = false;
}
void CRealTimcsEx::Start()
{
	if (m_bStart)
	{
		return;
	}
#ifdef Q_OS_WINDOWS
	QueryPerformanceCounter(&m_startTicks);
#else
    m_startTicks = QDateTime::currentMSecsSinceEpoch();
#endif
	m_bStart = true;
}
void CRealTimcsEx::Pause()
{
	if (!m_bStart)
	{ 
		return;
	}
#ifdef Q_OS_WINDOWS
	m_endTicks.QuadPart = 0;
	QueryPerformanceCounter(&m_endTicks);
	__int64 lltemp =
		(m_endTicks.QuadPart - m_startTicks.QuadPart);
	
	lltemp *= 1000000;
	lltemp /= m_freq.QuadPart;

	m_llMicrosecond += lltemp;

	m_dMillisecond += m_llMicrosecond/1000.0;

	m_startTicks.QuadPart = m_endTicks.QuadPart;
#else
    m_endTicks = QDateTime::currentMSecsSinceEpoch();
    qint64 lltemp = m_startTicks - m_endTicks;
    m_dMillisecond += lltemp;
    m_startTicks = m_endTicks;
#endif
}
void CRealTimcsEx::End()
{
	Pause();

	m_bStart = false;
}
double CRealTimcsEx::Gaps()
{
	return m_dMillisecond;
}
double CRealTimcsEx::GetCurrentGaps()
{
	Pause();
	return m_dMillisecond;
}
string CRealTimcsEx::Gapstr()
{
	char buff[TICKS_BUFFER_LEN_128] = { 0 };
    sprintf(
        buff,
		"[%s::%lld]\r\n", 
		m_name.c_str(), 
        (qint64)m_dMillisecond);

	return string(buff);
}
void CRealTimcsEx::AddGap(double dTicks)
{
	m_dMillisecond += dTicks;

	m_llMicrosecond += (dTicks * 1000);
}
